package io.mft.dev.base.config;

import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import cn.hutool.core.io.IoUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import io.mft.commons.exception.MFTException;
import io.mft.commons.util.xml.IOUtil;
import io.mft.dev.base.config.builder.CatalogApiBuilder;
import io.mft.dev.base.config.builder.CatalogApiBuilder.CatalogApiCollection;
import lombok.extern.slf4j.Slf4j;

/**
 * 本地API加载
 * 
 * @说明：TODO
 * @类型名称：LocalApiConfigProvideLoader
 * @创建者: 胡常建
 * @创建时间: 2021年8月16日 下午5:41:59
 * @修改者: 胡常建
 * @修改时间: 2021年8月16日 下午5:41:59
 */
@Slf4j
public class LocalApiConfigProvideLoader extends LocalConfigProvideLoader {

	public LocalApiConfigProvideLoader(ClassLoader classLoader) {
		super(classLoader);
	}

	@Override
	public Map<String, Object> load() {
		Map<String, Object> kv = new ConcurrentHashMap<String, Object>();
		CatalogApiBuilder catalogApiBuilder=new CatalogApiBuilder(classLoader);
		CatalogApiCollection catalogApiCollection=catalogApiBuilder.build();
		catalogApiCollection.getCatalogApis().forEach(catalogApi->{
			try {
				String apiPath="config/api/"+catalogApi.getSystemKey()+"/"+catalogApi.getModuleKey()+"/"+catalogApi.getApiFunctionType()+"/"+catalogApi.getKey()+".json";
				String locationPattern = "classpath*:"+apiPath;
				PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(new PathMatchingResourcePatternResolver());
				Resource[] resources = resolver.getResources(locationPattern);
				if (resources==null||resources.length==0) {
					throw new MFTException(-1,"未获取到接口配置[" + apiPath + "],请检查");
				}
				if (resources.length>1) {
					log.warn("API["+apiPath+"]配置数量:"+resources.length+",仅处理一个配置,请检查是否忽略");
				}
				Resource resource=resources[0];
				InputStream inputStream=resource.getInputStream();
				Charset charset = Charset.forName("UTF-8");
				String jsonText=IoUtil.read(inputStream, charset);
				JSONObject jsonObject = JSONUtil.parseObj(jsonText);
				String apiKey = jsonObject.getStr("key");
				if (!catalogApi.getKey().equals(apiKey)) {
					throw new MFTException(-1,"接口号[" + apiKey + "]与接口文件[" + apiPath+ "]名称不一致");
				}
				kv.put(apiKey, jsonObject.toString());
				log.warn("加载完毕API详细配置资源,路径["+resource.getURI().toURL().getPath()+"]");
			} catch (MFTException e) {
				log.error("",e);
			}catch (Exception e) {
				log.error("API-JSON实例化异常,编号[" + catalogApi.getKey() + "]",e);
			}
		});
		return kv;
	}
	@Override
	public String namespace() {
		return "api";
	}
}
